/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package simple.utils.httpclient;

import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpChunkAggregator;
import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
import org.jboss.netty.handler.codec.http.HttpResponseDecoder;
import org.jboss.netty.handler.ssl.SslHandler;
import org.jboss.netty.util.HashedWheelTimer;

import javax.net.ssl.SSLEngine;
import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author rehak
 */
public class HTTPClientPipelineFactory implements ChannelPipelineFactory, Closeable {

    private final LinkedBlockingQueue<DefaultHttpResponse> queue;
    private final HashedWheelTimer timer;
    //    private final long timeout;
    private final boolean useSSL;
    private final int maxContentLength;

    public HTTPClientPipelineFactory(LinkedBlockingQueue<DefaultHttpResponse> queue, boolean useSSL, HashedWheelTimer timer, int maxContentLength) {
        this.queue = queue;
//        this.timeout = timeout;
        this.useSSL = useSSL;
        this.timer = timer;
        this.maxContentLength = maxContentLength;
    }

    @Override
    public ChannelPipeline getPipeline() throws Exception {
        ChannelPipeline pipeline = Channels.pipeline();
        if (useSSL) {
            SSLEngine engine = AcceptAllSSLContextFactory.getSSLContext().createSSLEngine();
            engine.setEnabledCipherSuites(engine.getSupportedCipherSuites());
            engine.setUseClientMode(true);
            pipeline.addLast("ssl", new SslHandler(engine));
        }
//        pipeline.addLast("Timeout", new ReadTimeoutHandler(timer, timeout, TimeUnit.MILLISECONDS));        
        pipeline.addLast("HttpResponseDecoder", new HttpResponseDecoder());
        pipeline.addLast("HttpChunkAggregator", new HttpChunkAggregator(maxContentLength));
        pipeline.addLast("HttpRequestEncoder", new HttpRequestEncoder());
        // and then business logic.
        pipeline.addLast("handler", new HTTPClientHandler<>(queue, useSSL));
        return pipeline;
    }

    @Override
    public void close() throws IOException {
        timer.stop();
    }
}
